/*
 未来之窗库
 javascript query design by cyberwin
 2022-7-8 
*/

function $cq(cyberobjname){
    return  new cyberwin_query(cyberobjname);
}

function cyberwin_query(cyberobjname){//参数是变体变量
	/*
   this.elements=[];//选择器选择的元素扔到这个数组中
   // this.elements=[];//选择器选择的元素扔到这个数组中
  var idn= cyberobjname.startsWith("#");
  var obj_id=cyberobjname.replace("#","");

  var obj =document.getElementById(obj_id);
  return obj;*/
  this.elements=[];//选择器选择的元素扔到这个数组中
    switch(typeof cyberobjname){
        //如果参数是函数
        case 'function':
            myAddEvent(window,'load',cyberobjname);
            break;
        //如果参数是字符串
        case 'string2025':
            switch(cyberobjname.charAt(0)){
                case '#'://id选择器参数应该为#号之后的字符段
				    console.log("未来之窗操作器寻找id",cyberobjname.substring(1));
                    var obj=document.getElementById(cyberobjname.substring(1));
                    this.elements.push(obj);
					console.log("未来之窗操作器寻找id",obj);
                break;

                case '.'://class
			     {
                   // this.elements=getByClass(document,cyberobjname.substring(1));
				   this.elements = getSelectorByClassv2008(document,cyberobjname);
				 }
                    break;

                default://标签
                    this.elements=document.getElementsByTagName(cyberobjname);
            }
            break;
		case 'string':
		{
			this.elements = getSelectorALLv2025(document,cyberobjname);
		}
		 break;
        //如果参数是对象。
        case 'object':
            this.elements.push(cyberobjname);
            
    }

}


//取值方法
cyberwin_query.prototype.val=function(value){
    if(arguments.length==1){//当参数个数为2时，使用设置css的方法
        var i=0;
        for(i=0;i<this.elements.length;i++){
            this.elements[i].value=value;
        }
    }else{//只有一个参数时获取样式
        return this.elements[0].value;;
    }
};



//2022-7-8 样式
//css方法
cyberwin_query.prototype.css=function(attr,value){
    if(arguments.length==2){//当参数个数为2时，使用设置css的方法
        var i=0;
        for(i=0;i<this.elements.length;i++){
            this.elements[i].style[attr]=value;
            
        }
    }else{//只有一个参数时获取样式
        return getStyle(this.elements[0],attr);
    }
};



//eq选择器
cyberwin_query.prototype.eq=function(n){
    return new cyberwin_query(this.elements[n]);
}

// 
//对选择器函数绑定click事件
cyberwin_query.prototype.click=function(fn){
    var i=0;
    //对于返回器数组的内容
    for(i=0;i<this.elements.length;i++){
        myAddEvent(this.elements[i],'click',fn);
    }
}

cyberwin_query.prototype.find=function(str){
    var i=0;
    var aResult=[];//存放临时数据

    for(i=0;i<this.elements.length;i++){
        switch(str.charAt(0)){

            case '.'://class类
                var aEle=getByClass(this.elements[i],str.substring(1));
            aResult.concat(aEle);//桥接到aResult内。但是
            break;

            default://其它标签名(TagName)
                var aEle=this.elements[i].getElementsByTagName(str);
                appendArr(aResult,aEle);
        }
    }
    var newdQuery=new cyberwin_query();
    newdQuery.elements=aResult;
    return newdQuery;//保持可链。
}


//可重复调用的加载函数
function myAddEvent(obj,sEv,fn){
    if(obj.attachEvent){
        obj.attachEvent('on'+sEv,function(){
            fn.call(obj);//兼容ie
        });
    }else{
        obj.addEventListener(sEv,fn,false);
    }
}

//class选择器调用函数
function getByClass(oParent,sClass){
    var aEle=oParent.getElementsByTagName('*');//选择父元素的所有元素
    var aResult=[];
    var re=new RegExp('\\b'+sClass+'\\b','i');//正则边界
    var i=0;
    for(i=0;i<aEle.length;i++){
        if(re.test(aEle[i].className)){
            aResult.push(aEle[i]);
        }
    }
    return aResult;
}

//获取计算后的样式
function getStyle(obj,attr){
    //元素，样式
    if(obj.currentStyle){//兼容ie9及以下
        return obj.currentStyle[attr];
    }else{
        return getComputedStyle(obj,false)[attr];
    }
}


//对选择器函数绑定show/hide事件
cyberwin_query.prototype.show=function(){
    var i=0;
    //对于返回器数组的内容
    for(i=0;i<this.elements.length;i++){
        this.elements[i].style.display='block';
    }
}

cyberwin_query.prototype.hide=function(){
    var i=0;
    //对于返回器数组的内容
    for(i=0;i<this.elements.length;i++){
        this.elements[i].style.display='none';
    }
};

function getSelectorByClassv2008(oParent,sClass){
    //var aEle=oParent.getElementsByTagName('*');//选择父元素的所有元素
   // var aResult=[];
    //var re=new RegExp('\\b'+sClass+'\\b','i');//正则边界
	//var aEle= oParent.querySelector(sClass); 
	//querySelectorAll
	var Cyberwin_Ele= oParent.querySelectorAll(sClass); 
	//console.log("未来之窗操作器text",Cyberwin_Ele);

	var cyberwin_ret=[];
    var i=0;
    for(i=0;i<Cyberwin_Ele.length;i++){
		//console.log("未来之窗操作器text",Cyberwin_Ele[i]);
        //if(re.test(Cyberwin_Ele[i].className)){
            cyberwin_ret.push(Cyberwin_Ele[i]);
       // }
    }
    return cyberwin_ret;
}


function getSelectorALLv2025(oParent,sClass){
    //var aEle=oParent.getElementsByTagName('*');//选择父元素的所有元素
   // var aResult=[];
    //var re=new RegExp('\\b'+sClass+'\\b','i');//正则边界
	//var aEle= oParent.querySelector(sClass); 
	//querySelectorAll
	var Cyberwin_Ele= oParent.querySelectorAll(sClass); 
	//console.log("未来之窗操作器text",Cyberwin_Ele);

	var cyberwin_ret=[];
    var i=0;
    for(i=0;i<Cyberwin_Ele.length;i++){
		//console.log("未来之窗操作器text",Cyberwin_Ele[i]);
        //if(re.test(Cyberwin_Ele[i].className)){
            cyberwin_ret.push(Cyberwin_Ele[i]);
       // }
    }
    return cyberwin_ret;
}

//2025-8-29
//innerText innerHTML
cyberwin_query.prototype.text=function(value){
	console.log("未来之窗操作器text",this);
	const that=this;

    if(arguments.length==1){//当参数个数为2时，使用设置css的方法
        var i=0;
		console.log("未来之窗操作器text");
        for(i=0;i<that.elements.length;i++){
			console.log("未来之窗操作器",that.elements[i]);
            that.elements[i].innerText=value;
        }
    }else{//只有一个参数时获取样式
        return that.elements[0].innerText;;
    }
};

cyberwin_query.prototype.html=function(value){
	const that=this;
    if(arguments.length==1){//当参数个数为2时，使用设置css的方法
        var i=0;
        for(i=0;i<that.elements.length;i++){
            that.elements[i].innerHTML=value;
        }
    }else{//只有一个参数时获取样式
        return that.elements[0].innerHTML;;
    }
};

// 1. 添加each方法
cyberwin_query.prototype.each = function(callback) {
    if (typeof callback === 'function') {
        for (var i = 0; i < this.elements.length; i++) {
            // 执行回调函数，传入索引和当前元素，this指向当前元素
            callback.call(this.elements[i], i, this.elements[i]);
        }
    }
    return this; // 支持链式调用
};


//全局
// 2. AJAX相关功能
// 全局AJAX设置
var cyberwin_ajaxSettings = {
    type: 'GET',
    url: '',
    data: null,
    async: true,
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
    },
    error: function() {},
    success: function() {},
    complete: function() {}
};

// AJAX设置方法
$cq.ajaxSetup = function(options) {
    for (var key in options) {
        if (options.hasOwnProperty(key)) {
			console.log("配置",key);
            cyberwin_ajaxSettings[key] = options[key];
        }
    }
};

// AJAX核心方法
$cq.ajax = function(options) {
    // 合并配置，优先级：调用时传入 > 全局设置
    var settings = {};
    for (var key in cyberwin_ajaxSettings) {
        settings[key] = cyberwin_ajaxSettings[key];
    }
    for (var key in options) {
        if (options.hasOwnProperty(key)) {
            settings[key] = options[key];
        }
    }

    // 创建XMLHttpRequest对象
    var xhr;
    if (window.XMLHttpRequest) {
        xhr = new XMLHttpRequest();
    } else {
        // 兼容IE6及以下
        xhr = new ActiveXObject("Microsoft.XMLHTTP");
    }

    // 处理数据
    var dataStr = '';
    if (settings.data && typeof settings.data === 'object') {
        for (var key in settings.data) {
            if (settings.data.hasOwnProperty(key)) {
                dataStr += encodeURIComponent(key) + '=' + encodeURIComponent(settings.data[key]) + '&';
            }
        }
        dataStr = dataStr.slice(0, -1);
    }

    // 处理URL（GET方法时附加数据）
    var url = settings.url;
    if (settings.type.toUpperCase() === 'GET' && dataStr) {
        url += (url.indexOf('?') > -1 ? '&' : '?') + dataStr;
        dataStr = null; // GET方法不需要send数据
    }

    // 打开连接
    xhr.open(settings.type, url, settings.async);

    // 设置请求头
    for (var key in settings.headers) {
        if (settings.headers.hasOwnProperty(key)) {
			console.log("配置设置请求头",key);
            xhr.setRequestHeader(key, settings.headers[key]);
        }
    }

    // 处理响应
    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4) {
            // 调用完成回调
            settings.complete(xhr);
            
            if (xhr.status >= 200 && xhr.status < 300) {
                // 成功回调
                var responseData;
                try {
                    // 尝试解析JSON
                    responseData = JSON.parse(xhr.responseText);
                } catch (e) {
                    // 解析失败则返回原始文本
                    responseData = xhr.responseText;
                }
                settings.success(responseData, xhr.status, xhr);
            } else {
                // 错误回调
                settings.error(xhr, xhr.status, xhr.statusText);
            }
        }
    };

    // 发送请求
    xhr.send(dataStr);
    
    // 返回xhr对象，方便中断请求等操作
    return xhr;
};

// 快捷GET方法
$cq.get = function(url, data, success, dataType) {
    // 处理参数重载
    if (typeof data === 'function') {
        dataType = success;
        success = data;
        data = null;
    }
    
    return $cq.ajax({
        type: 'GET',
        url: url,
        data: data,
        success: success
    });
};

// 快捷POST方法
$cq.post = function(url, data, success, dataType) {
    // 处理参数重载
    if (typeof data === 'function') {
        dataType = success;
        success = data;
        data = null;
    }
    
    return $cq.ajax({
        type: 'POST',
        url: url,
        data: data,
        success: success
    });
};

 cyberwin_query.prototype.serializeJson=function(){  
        var serializeObj={};  
        var array=this.serializeArray();  
        $(array).each(function(){  
            if(serializeObj[this.name]){  
                if($.isArray(serializeObj[this.name])){  
                    serializeObj[this.name].push(this.value);  
                }else{  
                    serializeObj[this.name]=[serializeObj[this.name],this.value];  
                }  
            }else{  
                serializeObj[this.name]=this.value;   
            }  
        });  
        return serializeObj;  
    }; 
 cyberwin_query.prototype.WLZC_serializeJson2024=function(){  
        var wlzc_serializeObj={};  
        var array=this.serializeArray();  
        $(array).each(function(){ 
			var wlzc_ei_name = this.name;
			//ymethod[1][paymethod_id]
			var ie = wlzc_ei_name.indexOf("[");
			if(ie >=0){
				//console.log("未来之窗编码，存在" + wlzc_ei_name);
				var wlzc_ei_name_yh1 =wlzc_ei_name.replace(/]/g,"");
				const wlzc_ei_name_Array = wlzc_ei_name_yh1.split("[");
				//console.log("未来之窗编码，分组");
				const  wlzc_ei_len = wlzc_ei_name_Array.length;
				console.log(wlzc_ei_name_Array);
				if(wlzc_ei_len == 3){
					var array_1 =wlzc_ei_name_Array[0];
					var array_2 =wlzc_ei_name_Array[1];
					var array_3 =wlzc_ei_name_Array[2];
					//错误 wlzc_serializeObj[array_1][array_2][array_3]=this.value;  
					//var jsonobj = array_2[array_3]=this.value;  
					var jsonobj_3=Array();
                    jsonobj_3[array_3]=this.value;  
					//console.log("未来之窗编码，分组jsonobj_3");
					//console.log(jsonobj_3);

					var jsonobj_2=Array();
                    jsonobj_2[array_2] = jsonobj_3;  
					//console.log("未来之窗编码，分组jsonobj_2");
					//console.log(jsonobj_2);
					//wlzc_serializeObj[array_1]=jsonobj_2;
					if(wlzc_serializeObj[array_1]){ 
                       
					}else{
					//	wlzc_serializeObj[array_1]=[];  
						wlzc_serializeObj[array_1]={};  
					}

					if(wlzc_serializeObj[array_1][array_2]){ 
                       
					}else{
						// wlzc_serializeObj[array_1][array_2]=[]; 
						  wlzc_serializeObj[array_1][array_2]={}; 
					}

					if(wlzc_serializeObj[array_1][array_2][array_3]){ 
                       wlzc_serializeObj[array_1][array_2][array_3]=this.value;  
					}else{
						 wlzc_serializeObj[array_1][array_2][array_3]=this.value;  
						 
					}

				}
			}else{
               //未来之窗
				if(wlzc_serializeObj[this.name]){  
					if($.isArray(wlzc_serializeObj[this.name])){  
						wlzc_serializeObj[this.name].push(this.value);  
					}else{  
						wlzc_serializeObj[this.name]=[wlzc_serializeObj[this.name],this.value];  
					}  
				}else{  
					wlzc_serializeObj[this.name]=this.value;   
				}

			}
        });  
        return wlzc_serializeObj;  
    }; 

// 3. 添加WLZC_serializeJson方法
cyberwin_query.prototype.WLZC_serializeJson = function() {
    var wlzc_serializeObj = {};
    var elements = this.elements[0] ? this.elements[0].elements : [];
    
    // 收集表单数据
    var array = [];
    for (var i = 0; i < elements.length; i++) {
        var elem = elements[i];
        // 跳过禁用的元素和没有name属性的元素
        if (elem.disabled || !elem.name) continue;
        
        // 处理复选框和单选按钮
        if ((elem.type === 'checkbox' || elem.type === 'radio') && !elem.checked) continue;
        
        array.push({
            name: elem.name,
            value: elem.value
        });
    }
    
    // 处理数据结构
    for (var i = 0; i < array.length; i++) {
        var item = array[i];
        var wlzc_ei_name = item.name;
        var ie = wlzc_ei_name.indexOf("[");
        
        if (ie >= 0) {
            // 处理数组形式的name，如ymethod[1][paymethod_id]
            var wlzc_ei_name_yh1 = wlzc_ei_name.replace(/]/g, "");
            var wlzc_ei_name_Array = wlzc_ei_name_yh1.split("[");
            var wlzc_ei_len = wlzc_ei_name_Array.length;
            
            if (wlzc_ei_len === 3) {
                var array_1 = wlzc_ei_name_Array[0];
                var array_2 = wlzc_ei_name_Array[1];
                var array_3 = wlzc_ei_name_Array[2];
                
                // 初始化嵌套对象
                if (!wlzc_serializeObj[array_1]) {
                    wlzc_serializeObj[array_1] = {};
                }
                if (!wlzc_serializeObj[array_1][array_2]) {
                    wlzc_serializeObj[array_1][array_2] = {};
                }
                
                // 赋值
                wlzc_serializeObj[array_1][array_2][array_3] = item.value;
            }
        } else {
            // //未来之窗
            if (wlzc_serializeObj[wlzc_ei_name]) {
                if (Array.isArray(wlzc_serializeObj[wlzc_ei_name])) {
                    wlzc_serializeObj[wlzc_ei_name].push(item.value);
                } else {
                    wlzc_serializeObj[wlzc_ei_name] = [wlzc_serializeObj[wlzc_ei_name], item.value];
                }
            } else {
                wlzc_serializeObj[wlzc_ei_name] = item.value;
            }
        }
    }
    
    return wlzc_serializeObj;
};


  